package com.ruoyi.business.utils;

import org.apache.commons.lang3.StringUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * 字段名转换工具类
 */
public class FieldNameConverter {
    /**
     * 下划线转驼峰法
     *
     * @param line
     *            源字符串
     * @param smallCamel
     *            大小驼峰,是否为小驼峰
     * @return 转换后的字符串
     */
    public static String underline2Camel(String line, boolean smallCamel) {
        if (line == null || "".equals(line)) {
            return "";
        }
        String[] sourceArray = StringUtils.split(line, "\r\n");
        StringBuffer sb = new StringBuffer();
        for(String source:sourceArray){
            if(!StringUtils.isEmpty(source)){
                Pattern pattern = Pattern.compile("([A-Za-z\\d]+)(_)?");
                Matcher matcher = pattern.matcher(source);
                while (matcher.find()) {
                    String word = matcher.group();
                    sb.append(smallCamel && matcher.start() == 0 ? Character
                            .toLowerCase(word.charAt(0)) : Character.toUpperCase(word
                            .charAt(0)));
                    int index = word.lastIndexOf('_');
                    if (index > 0) {
                        sb.append(word.substring(1, index).toLowerCase());
                    } else {
                        sb.append(word.substring(1).toLowerCase());
                    }
                }
            }
            if(sourceArray.length>1) {
                sb.append("\r\n");
            }
        }
        return sb.toString();
    }

    /**
     * 驼峰法转下划线
     *
     * @param line
     *            源字符串
     * @return 转换后的字符串
     */
    public static String camel2Underline(String line) {
        if (line == null || "".equals(line)) {
            return "";
        }
        String[] sourceArray = StringUtils.split(line, "\r\n");
        StringBuffer sb = new StringBuffer();
        for(String source:sourceArray){
            if(!StringUtils.isEmpty(source)){
                source = String.valueOf(source.charAt(0)).toUpperCase().concat(
                        source.substring(1));
                Pattern pattern = Pattern.compile("[A-Z]([a-z\\d]+)?");
                Matcher matcher = pattern.matcher(source);
                while (matcher.find()) {
                    String word = matcher.group();
                    sb.append(word.toUpperCase());
                    sb.append(matcher.end() == source.length() ? "" : "_");
                }
            }
            if(sourceArray.length>1) {
                sb.append("\r\n");
            }
        }
        return sb.toString();
    }
}
